package com.clockey.server.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.clockey.server.httpserver.netty.Request;
import com.clockey.server.httpserver.netty.bean.Modle;
import com.clockey.server.httpserver.netty.mvc.Controller;
import com.clockey.server.service.EventService;
import com.clockey.server.util.ConstantUtil;
import com.clockey.server.util.redis.RedisUtil;

public class UploadMsgController implements Controller {
	
	protected Logger logger = LoggerFactory.getLogger(getClass()); 
	
	private EventService eventService;

	public void handleMsg(Request request, Modle modle) {
		String uploadMsgXml = request.getQueryString();
		logger.info("recieved xml: {}",uploadMsgXml);
		Document document = Jsoup.parse(uploadMsgXml, "UTF-8");
		String phoneNum = document.select("fromNum").text();
		String msgContent = document.select("content").text();
		logger.info("get phoneNum={}, msgContent={}",phoneNum,msgContent);
		// 如果是1就确定参加
		if (StringUtils.equalsIgnoreCase(msgContent, "1")) {
			Map<String, Object> map = new HashMap<String, Object>();
			// 从缓存中取出
			Jedis jedis = RedisUtil.getJedis();
			/*******userObject是这样的格式
			JSONObject userObject = new JSONObject();
			userObject.put("userId", user.getId());
			userObject.put("userName", user.getUserName());
			userObject.put("avatar", user.getAvatar());
			userObject.put("phone", user.getPhone());
			userObject.put("cid", user.getCid());*****/
			
			String redisKey = ConstantUtil.KEY_PREFIX_SENDED_USER + phoneNum;
			String userObjectStr = jedis.get(redisKey);
			JSONObject userObject = JSON.parseObject(userObjectStr);
			if(userObject != null){
				map.put("userId", userObject.get("userId"));
				map.put("eventId", userObject.get("eventId"));
				map.put("handResult", 1);
				eventService.handEventByInviter(map);
				//jedis.del(redisKey);不能删,万一用户还回复其他活动
			}else{
				logger.error("get user from cache failed redisKey={}",redisKey);
			}
			jedis.close();//释放会池子
		}
	}

	public EventService getEventService() {
		return eventService;
	}

	public void setEventService(EventService eventService) {
		this.eventService = eventService;
	}

}
